package com.exercises;

import java.util.Arrays;

class Exercise1011 {
    public static void main(String[] args) {
        System.out.println(shipWithinDays(new int[]{1,2,3,1,1}, 4));
    }

    public static int shipWithinDays(int[] weights, int count) {
        int min = Arrays.stream(weights).max().getAsInt(), max = Arrays.stream(weights).sum();
        if (count == 1) return max;
        int j = 0;
        while (min < max) {
            j = (min + max) / 2;
            int less = j, useCount = 1;
            for (int i = 0; i < weights.length; i++) {
                if (less - weights[i] < 0) {
                    less = j;
                    useCount++;
                }
                less -= weights[i];
            }
            if (useCount > count) min = j + 1;
            if (useCount <= count) max = j;

        }
        return max;
    }
}

